package com.chengxiaoxiao.libarypartner.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.chengxiaoxiao.libarypartner.R;
import com.chengxiaoxiao.libarypartner.constants.AppConsrants;
import com.chengxiaoxiao.libarypartner.domain.Author;
import com.chengxiaoxiao.libarypartner.domain.Books;
import com.chengxiaoxiao.libarypartner.domain.ListBooksCategory;
import com.chengxiaoxiao.libarypartner.utils.ApiAddress;
import com.chengxiaoxiao.libarypartner.utils.LoadDialogUtils;
import com.chengxiaoxiao.libarypartner.utils.SPUtils;
import com.chengxiaoxiao.libarypartner.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.image.SmartImageView;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CategoryActivity extends Activity
{
    private ListView listBooks;
    private TextView textTitle;

    private List<ListBooksCategory> list = new ArrayList<>();

    private List<Books> listBook;




    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        //ToastUtils.makeText(CategoryActivity.this, id);

        listBooks = (ListView) findViewById(R.id.listBooks);
        textTitle = (TextView)findViewById(R.id.textTitle);

        Intent intent = getIntent();
        String method = intent.getStringExtra("method");

        LoadDialogUtils.show(CategoryActivity.this,"","加载中...");
        if("category".equalsIgnoreCase(method))
        {
            String id = intent.getStringExtra("categoryId");

            /**
             * 加载分类下的图书
             */
            loadBooks(id);

            listBooks.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    Intent intent = new Intent(CategoryActivity.this, BookActivity.class);

                    intent.putExtra(AppConsrants.BOOK_ID,list.get(position).getId()+"");
                    startActivity(intent);
                }
            });



        }
        else if ("bookRank".equalsIgnoreCase(method))
        {

            loadBookRank();

            listBooks.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    Intent intent = new Intent(CategoryActivity.this, BookActivity.class);

                    intent.putExtra(AppConsrants.BOOK_ID,listBook.get(position).getId()+"");
                    startActivity(intent);
                }
            });

        }
        else if("newbook".equalsIgnoreCase(method))
        {
            loadNewBooks();
            listBooks.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                    Intent intent = new Intent(CategoryActivity.this, BookActivity.class);

                    intent.putExtra(AppConsrants.BOOK_ID,listBook.get(position).getId()+"");
                    startActivity(intent);
                }
            });
        }else if("hotauthor".equalsIgnoreCase(method))
        {
            hotAuthor();
        }

        LoadDialogUtils.hidden();



    }

    /**
     * 获取热门作者
     */
    private void hotAuthor()
    {
        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=hotAuthor", new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);
                try
                {
                    JSONArray jsonArray = new JSONArray(body);

                    listAuthor = new ArrayList<Author>();

                    for (int i = 0; i < jsonArray.length(); i++)
                    {

                        JSONObject jsonObj = jsonArray.getJSONObject(i);

                        String name = jsonObj.getString("name");
                        String src = jsonObj.getString("src");
                        Author author = new Author(name, src);

                        listAuthor.add(author);
                    }

                    listBooks.setAdapter(new HotAuthorAdapter());


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(CategoryActivity.this, "获取新版本失败");
            }
        });

    }
    private List<Author> listAuthor;

    /**
     * 热门作者
     */
    class HotAuthorAdapter extends BaseAdapter
    {
        @Override
        public int getCount()
        {
            return listAuthor.size();
        }

        @Override
        public Object getItem(int position)
        {
            return listAuthor.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = View.inflate(CategoryActivity.this, R.layout.list_item_hot, null);

            TextView textName = (TextView) view.findViewById(R.id.textName);
            SmartImageView image = (SmartImageView) view.findViewById(R.id.ivIcon);

            Author author = listAuthor.get(position);
            textName.setText(author.getName());
            image.setImageUrl(author.getSrc());

            return view;
        }
    }

    /**
     * 新书榜
     */
    private void loadNewBooks()
    {
        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=newBook", new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);
                try
                {
                    JSONArray jsonArray = new JSONArray(body);

                    listBook = new ArrayList<Books>();

                    for (int i = 0; i < jsonArray.length(); i++)
                    {

                        JSONObject jsonObj = jsonArray.getJSONObject(i);


                        long id = jsonObj.getInt("id");
                        String bookName = jsonObj.getString("bookName");
                        String author = jsonObj.getString("author");
                        String categoryName = jsonObj.getString("categoryName");
                        String imagesPath = jsonObj.getString("imagesPath");
                        String publisherName = jsonObj.getString("publisherName");
                        long number = jsonObj.getInt("number");

                        String address = jsonObj.getString("address");
                        Books book = new Books(id, bookName, author, categoryName, imagesPath, number, address, publisherName);
                        listBook.add(book);
                    }

                    listBooks.setAdapter(new MyHotAdapter());


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(CategoryActivity.this, "网络连接错误");
            }
        });
    }

    /**
     * 图书榜
     */
    private void loadBookRank()
    {
        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=hotBook", new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);
                try
                {
                    JSONArray jsonArray = new JSONArray(body);

                    listBook = new ArrayList<Books>();

                    for (int i = 0; i < jsonArray.length(); i++)
                    {

                        JSONObject jsonObj = jsonArray.getJSONObject(i);


                        long id = jsonObj.getInt("id");
                        String bookName = jsonObj.getString("bookName");
                        String author = jsonObj.getString("author");
                        String categoryName = jsonObj.getString("categoryName");
                        String imagesPath = jsonObj.getString("imagesPath");
                        String publisherName = jsonObj.getString("publisherName");
                        long number = jsonObj.getInt("number");

                        String address = jsonObj.getString("address");
                        Books book = new Books(id, bookName, author, categoryName, imagesPath, number, address, publisherName);
                        listBook.add(book);
                    }

                    listBooks.setAdapter(new MyHotAdapter());


                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(CategoryActivity.this, "网络连接错误");
            }
        });
    }


    class MyHotAdapter extends BaseAdapter
    {

        @Override
        public int getCount()
        {
            return listBook.size();

        }

        @Override
        public Object getItem(int position)
        {
            return listBook.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if (convertView == null)
            {
                view = View.inflate(CategoryActivity.this, R.layout.list_item_category_books, null);
            } else
            {
                view = convertView;
            }

            SmartImageView imageIcon = (SmartImageView) view.findViewById(R.id.ivIcon);
            TextView textName = (TextView) view.findViewById(R.id.textName);
            TextView textAuthor = (TextView) view.findViewById(R.id.textAuthor);
            TextView textPublisher = (TextView) view.findViewById(R.id.textPublisher);
            TextView textNumber = (TextView) view.findViewById(R.id.textNumber);
            TextView textAddress = (TextView) view.findViewById(R.id.textAddress);

            Books item = listBook.get(position);


            textName.setText(item.getBookName());
            textAuthor.setText("作者："+item.getAuthor());
            textPublisher.setText("出版社："+item.getCategoryName());
            textNumber.setText("数量："+item.getNumber() + "");
            textAddress.setText(item.getAddress());
            imageIcon.setImageUrl(item.getImagesPath());


            return view;
        }
    }


    /**
     * 加载分类下书籍
     * @param id
     */
    private void loadBooks(String id)
    {
        final AsyncHttpClient client = new AsyncHttpClient();
        client.get(ApiAddress.getApiDomain() + "/client/ClientServlet?op=getBooksbyCategory&id=" + id, new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody)
            {

                String body = new String(responseBody);
                try
                {
                    JSONArray jsonArray = new JSONArray(body);


                    for (int i = 0; i < jsonArray.length(); i++)
                    {

                        JSONObject jsonObj = jsonArray.getJSONObject(i);

                        int id = jsonObj.getInt("id");
                        String author = jsonObj.getString("author");
                        String bookName = jsonObj.getString("bookName");
                        int number = jsonObj.getInt("number");
                        String categporyName = jsonObj.getString("categoryName");
                        String publisherName = jsonObj.getString("publisherName");
                        String imagesPath = jsonObj.getString("imagesPath");
                        String address = jsonObj.getString("address");

                        if(i==0)
                        {
                            textTitle.setText(categporyName+"书籍");
                        }


                        //TODO:增加对图片和所在位置的判断
                        ListBooksCategory book = new ListBooksCategory(id, bookName, author,publisherName , imagesPath, number, address);

                        list.add(book);
                    }

                    listBooks.setAdapter(new MyListBooksAdapter());






                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
            {
                //LoadDialogUtils.hidden();
                ToastUtils.makeText(CategoryActivity.this, "网络连接错误");
            }
        });
    }


    /**
     * 分类书籍的Adapter
     */
    class MyListBooksAdapter extends BaseAdapter
    {

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public Object getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if (convertView == null)
            {
                view = View.inflate(CategoryActivity.this, R.layout.list_item_category_books, null);
            } else
            {
                view = convertView;
            }

            SmartImageView imageIcon = (SmartImageView) view.findViewById(R.id.ivIcon);
            TextView textName = (TextView) view.findViewById(R.id.textName);
            TextView textAuthor = (TextView) view.findViewById(R.id.textAuthor);
            TextView textPublisher = (TextView) view.findViewById(R.id.textPublisher);
            TextView textNumber = (TextView) view.findViewById(R.id.textNumber);
            TextView textAddress = (TextView) view.findViewById(R.id.textAddress);
            ImageView imageCart = (ImageView)view.findViewById(R.id.imageCart);


            final ListBooksCategory item = list.get(position);


            textName.setText(item.getBookName());
            textAuthor.setText("作者："+item.getAuthor());
            textPublisher.setText("出版社："+item.getPublisher());
            textNumber.setText("数量："+item.getNumber() + "");
            textAddress.setText(item.getAddress());
            imageIcon.setImageUrl(item.getImagePath());

            imageCart.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    //添加到借书单
                    String ids =SPUtils.getString(AppConsrants.BORROW_LIST_ID,"",CategoryActivity.this);
                    if(!ids.contains(item.getId()+""))
                    {
                        SPUtils.putString(AppConsrants.BORROW_LIST_ID,ids+","+item.getId(),CategoryActivity.this);
                    }

                    ToastUtils.makeText(CategoryActivity.this,"书籍已成功添加到借书单");
                }
            });


            return view;
        }
    }
}
